<template>
  <el-dialog v-model="dialogVisible" title="新增签字" width="760" :before-close="close"  append-to="body">
    <div class="sign-box padding">
      <Vue3Sign ref="signRef" :canvas-width="700" :canvas-height="350" @on-done="handleDone" :footer="false" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="clear" type="danger" plain>清空</el-button>
        <el-button type="primary" @click="confirm"> 保存签字 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/store/user';
import axios from 'axios';

const props = defineProps({
  uploadType: {
    type: String,
    default: ''
  },
  keyname: {
    type: String,
    default: ''
  }
})
const dialogVisible = ref(false)
const signRef = ref(null)

function open() {
  dialogVisible.value = true
  clear()
}

function close() {
  dialogVisible.value = false
}

const handleDone = (img) => {
  console.log('签名结果:', img)
}
// 清空签名
function clear() {
   signRef.value?.clear()
}
async function confirm() {
  console.log('confirm', signRef.value)
  let base64 = await signRef.value.done()
  console.log('res', base64)
  // 转换为Blob用于上传
  const blob = base64ToBlob(base64)
  await uploadSignature(blob)
}

// Base64转Blob
const base64ToBlob = (base64) => {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], { type: mime })
}

// 上传到服务端
const uploadSignature = async (blob) => {
  const formData = new FormData()
  const filename = `${Date.now()}.png`
  formData.append('file', blob, filename)
  formData.append('type', props.uploadType)

  const loginInfo = useUserStore().loginInfo || {}

  const response = await axios.post('/api/attachmentUpload/attachmentUpload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      username: loginInfo.username || '',
      password: loginInfo.password || '',
    },
  })
  console.log('response', response)
  if (response.data.code == '1' && response.data.data) {
   emits('saveSign',response.data.data.accessoryId,props.keyname,response.data.data.accessoryUrl)
  }
}
const emits = defineEmits(['saveSign'])
defineExpose({
  open,
  close
})
</script>